﻿using B.S.Orders.Domain;
using B.S.Orders.ErrorCord;
using B.S.Orders.Read.Api.Application.Commands.OutsourcingCommand;
using MediatR;
using SqlSugar;

namespace B.S.Orders.Read.Api.Application.CommandsHander.OutsourcingCommandHandler
{
    public class GetOutsourcingCommandHandler : IRequestHandler<GetOutsourcingCommand, APIResult<APIPaging<Outsourcing>>>
    {
        private readonly ISqlSugarClient db;

        public GetOutsourcingCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<APIResult<APIPaging<Outsourcing>>> Handle(GetOutsourcingCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<Outsourcing>> result = new APIResult<APIPaging<Outsourcing>>();
            result.Code = APIEnum.success;
            result.Msg = "查询显示成功";
            var list = db.Queryable<Outsourcing>();

            if (!string.IsNullOrEmpty(request.AssociatedProjects))
            {
                list = list.Where(p => p.AssociatedProjects == request.AssociatedProjects);
            }
            if (!string.IsNullOrEmpty(request.DocumentSubject))
            {
                list = list.Where(p => p.DocumentSubject == request.DocumentSubject);
            }
            if (!string.IsNullOrEmpty(request.DocumentNumber))
            {
                list = list.Where(p => p.DocumentNumber == request.DocumentNumber);
            }
            if (!string.IsNullOrEmpty(request.AssociateProductionOrder))
            {
                list = list.Where(p => p.AssociateProductionOrder == request.AssociateProductionOrder);
            }
            if (!string.IsNullOrEmpty(request.Processors))
            {
                list = list.Where(p => p.Processors == request.Processors);
            }
            if (!string.IsNullOrEmpty(request.PreparationDocumentsPerson))
            {
                list = list.Where(p => p.PreparationDocumentsPerson == request.PreparationDocumentsPerson);
            }
            if (request.FriPreparationDocumentsDate != null)
            {
                list = list.Where(p => p.PreparationDocumentsDate >= request.FriPreparationDocumentsDate);
            }
            if (request.EndPreparationDocumentsDate != null)
            {
                list = list.Where(p => p.PreparationDocumentsDate <= request.EndPreparationDocumentsDate);
            }
            int TotalCount = list.Count();
            int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(p => p.OutsourcingId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            APIPaging<Outsourcing> paging = new APIPaging<Outsourcing>();
            paging.TotalCount = TotalCount;
            paging.TotalPage = TotalPage;
            paging.list = list.ToList();

            result.Data = paging;

            return await Task.FromResult(result);
        }
    }
}
